package com.lehecai.ucenter.action.user;

import com.google.common.collect.Lists;
import com.lehecai.core.EnabledStatus;
import com.lehecai.core.YesNoStatus;
import com.lehecai.core.type.ucenter.EducationDegreeType;
import com.lehecai.core.type.ucenter.MaritalStatus;
import com.lehecai.core.type.ucenter.SexType;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreDateUtils;
import com.lehecai.core.util.CoreFileUtils;
import com.lehecai.core.util.CoreStringUtils;
import com.lehecai.ucenter.action.BaseAction;
import com.lehecai.ucenter.dao.QueryParam;
import com.lehecai.ucenter.entity.app.App;
import com.lehecai.ucenter.entity.permission.Role;
import com.lehecai.ucenter.entity.permission.User;
import com.lehecai.ucenter.entity.permission.UserApp;
import com.lehecai.ucenter.entity.permission.UserRole;
import com.lehecai.ucenter.export.UsersExport;
import com.lehecai.ucenter.service.app.AppService;
import com.lehecai.ucenter.service.permission.RoleService;
import com.lehecai.ucenter.service.permission.UserService;
import com.lehecai.ucenter.utils.PageBean;
import com.lehecai.ucenter.utils.PageUtil;
import com.opensymphony.xwork2.Action;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class UserAction extends BaseAction {
	private static final long serialVersionUID = -8830679912602886965L;
	
	private UserService userService;
	private AppService appService;
	private RoleService roleService;
	
	private User user;
	private App app;
	private Role role;
	private List<User> users;
	private List<Role> roles;
	private List<App> dispatchedApps;
	private List<App> waitingApps;
	
	private String username;
	private String name;
	private String conPassword;
	private String conOpPwd;
	private int enabledValue;
	private int sexTypeValue;
	private int educationDegreeValue;
	private int maritalStatusValue;
	
	private String saveDir;
	private File pic;
	private String picFileName;
	private String fileName;
	private InputStream inputStream;
	private int page;
	private String modFlag;
	private Long uid;
	private Integer queryEnabledValue;

	private Long roleId;
	
	public String handle() {
		HttpServletRequest request = ServletActionContext.getRequest();
		enabledValue = EnabledStatus.ALL.getValue();
		QueryParam qp = new QueryParam();
		PageBean pageBean = super.getPageBean();
		if (StringUtils.isNotEmpty(modFlag) && modFlag.equals("0")) {
			if (page != 0) {
				if (pageBean.getPage() != page ) {
					pageBean.setPage(page);
				}
			}
		}
		qp.setPageBean(pageBean);
		if(!StringUtils.isEmpty(name)){
			if (uid != null) {
				User sUser = userService.get(uid);
				if (sUser != null) {
					name = sUser.getName();
				}
			}
			qp.setParameter(User.NAME_PROPERTY_NAME, name);
		}
		if(!StringUtils.isEmpty(username)){
			qp.setParameter(User.USER_NAME_PROPERTY_NAME, username);
		}
		//是否有效
		if (queryEnabledValue != null && queryEnabledValue.intValue() != -1) {
			qp.setParameter(User.ENABLED_PROPERTY_NAME, EnabledStatus.getItem(queryEnabledValue));
			enabledValue = queryEnabledValue.intValue();
		}
		users = userService.findList(qp);
        if (users != null) {
            Map<Long, Role> roleMap = userService.getUserRoleMap();
            for (User user : users) {
                Role role = roleMap.get(user.getId());
                if (role != null) {
                    user.setRoleName(role.getName());
                }
            }
        }
		String pageString = PageUtil.getPageString(request, qp.getPageBean());
		super.setPageString(pageString);
		return "list";
	}
	
	public String input() {
		if (user != null && user.getId() != null) {
			user = userService.get(user.getId());
		} else {
			user = new User();
			user.setEnabled(EnabledStatus.ENABLED);
			user.setEducationDegree(EducationDegreeType.BACHELOR);
			user.setMaritalStatus(MaritalStatus.unmarried);
			user.setSex(SexType.MALE);
			roles = roleService.getAll();
		}
		return "inputForm";
	}
	
	public void check() {
		logger.info("进入检验用户名是否存在");
		HttpServletResponse response = ServletActionContext.getResponse();
		boolean flag = true;
		User sUser = userService.findByUsername(user.getUsername());
		if (sUser != null && sUser.getId() != null) {
			flag = false;
		}
		super.writeRs(response, flag + "");
	}
	
	public String manage() {
		if (user != null) {
			if (StringUtils.isEmpty(user.getName())) {
				logger.error("添加用户，用户姓名为空");
				super.setErrorMessage("用户姓名不能为空");
				return "inputForm";
			}
			if (user.getId() == null) {
				User sUser = userService.findByUsername(user.getUsername());
				if (sUser != null && sUser.getId() != null) {
					logger.error("用户名已被使用");
					super.setErrorMessage("用户名已被使用");
					return "inputForm";
				}
				if (StringUtils.isEmpty(user.getPassword())) {
					logger.error("密码为空");
					super.setErrorMessage("密码不能为空");
					return "inputForm";
				}
				if (StringUtils.isEmpty(conPassword)) {
					logger.error("确认密码为空");
					super.setErrorMessage("确认密码不能为空");
					return "inputForm";
				}
				if (!(user.getPassword()).equals(conPassword)) {
					logger.error("两次密码输入不一致");
					super.setErrorMessage("两次密码输入不一致");
					return "inputForm";
				}
				if (!StringUtils.isEmpty(user.getOpPwd()) && !StringUtils.isEmpty(conOpPwd) && !(user.getPassword()).equals(conPassword)) {
					logger.error("两次确认密码输入不一致");
					super.setErrorMessage("两次确认密码输入不一致");
					return "inputForm";
				}
				if (roleId == null) {
					logger.error("用户角色不能为空");
					super.setErrorMessage("用户角色不能为空");
					return "inputForm";
				}
				Role role = roleService.get(roleId);
				if (role == null) {
					logger.error("根据roleId未能查询到相关角色");
					super.setErrorMessage("根据roleId未能查询到相关角色");
					return "inputForm";
				}
				user.setPassword(CoreStringUtils.md5(user.getPassword(), CharsetConstant.CHARSET_UTF8));
				user.setOpPwd(CoreStringUtils.md5(user.getOpPwd(), CharsetConstant.CHARSET_UTF8));
				user.setEnabled(EnabledStatus.getItem(enabledValue));
				user.setSex(SexType.getItem(sexTypeValue));
				user.setEducationDegree(EducationDegreeType.getItem(educationDegreeValue));
				user.setMaritalStatus(MaritalStatus.getItem(maritalStatusValue));
				user.setUpdatedTime(new Date());
				User userSave = userService.update(user);
				UserRole userRole = new UserRole(userSave.getId(), role.getId());
				userService.update(userRole);
				super.setForwardUrl("/user/user.do");
				return "success";
			} else {
				User sUser = userService.get(user.getId());
				if (sUser == null || sUser.getId() == null) {
					logger.error("用户不存在");
					super.setErrorMessage("用户不存在");
					return "failure";
				}
				sUser.setName(user.getName());
				sUser.setMobile(user.getMobile());
				sUser.setTel(user.getTel());
				sUser.setEmail(user.getEmail());
				sUser.setMemo(user.getMemo());
				sUser.setQq(user.getQq());
				sUser.setWeibo(user.getWeibo());
				sUser.setBirthday(user.getBirthday());
				sUser.setEntryDate(user.getEntryDate());
				sUser.setLeaveDate(user.getLeaveDate());
				sUser.setContractBeginDate(user.getContractBeginDate());
				sUser.setContractEndDate(user.getContractEndDate());
				sUser.setRegularizationDate(user.getRegularizationDate());
				sUser.setNation(user.getNation());
				sUser.setUniversity(user.getUniversity());
				sUser.setSex(SexType.getItem(sexTypeValue));
				sUser.setEducationDegree(EducationDegreeType.getItem(educationDegreeValue));
				sUser.setMaritalStatus(MaritalStatus.getItem(maritalStatusValue));
				sUser.setEnabled(EnabledStatus.getItem(enabledValue));
				sUser.setUpdatedTime(new Date());
				sUser.setPicPath(user.getPicPath());
				sUser.setClientIp(user.getClientIp());
				sUser.setResourceIp(user.getResourceIp());
				userService.update(sUser);
			}
		} else {
			logger.error("添加用户错误，提交表单为空");
			super.setErrorMessage("添加用户错误，提交表单不能为空");
			return "failure";
		}
		String url = "/user/user.do?&page=" + page +"&username=" + username + "&uid=" + user.getId() + "&modFlag=0" + "&name=" + name;
		if (queryEnabledValue != null) {
			url += "&queryEnabledValue=" + queryEnabledValue;
		}
		super.setForwardUrl(url);
		return "success";
	}

	public String disableOtp() {
		HttpServletResponse response = ServletActionContext.getResponse();
		JSONObject rs = new JSONObject();
		rs.put("flag", "0");
		String msg = "";
		if (user == null || user.getId() == null) {
			logger.error("未能获取用户id");
			msg = "未能获取用户id";
		}
		User sUser = userService.get(user.getId());
		if (sUser == null) {
			logger.error("未能根据id查询到相应用户。");
			msg = "未能根据id查询到相应用户。";
		}
		if (StringUtils.isNotEmpty(msg)) {
			rs.put("msg", msg);
			rs.put("flag", "1");
			writeRs(ServletActionContext.getResponse(), rs);
			return Action.NONE;
		}
		if (sUser.getOtp().getValue() == YesNoStatus.YES.getValue()) {
			sUser.setOtp(YesNoStatus.NO);
			userService.update(sUser);
		}
		writeRs(response, rs);
		return Action.NONE;
	}
	
	public String view() {
		logger.info("进入查看用户详情");
		if (user != null && user.getId() != null) {
			user = userService.get(user.getId());
		} else {
			logger.error("查看用户详情，编码为空");
			super.setErrorMessage("查看用户详情，编码为空");
			return "failure";
		}
		logger.info("查看用户详情结束");
		return "view";
	}
	
	public String del() {
		logger.info("进入删除用户");
		if (user != null && user.getId() != null) {
			user = userService.get(user.getId());
			userService.delete(user);
		} else {
			logger.error("删除用户，编码为空");
			super.setErrorMessage("删除用户，编码不能为空");
			return "failure";
		}
		super.setForwardUrl("/user/user.do");
		logger.info("删除用户结束");
		return "forward";
	}
	
	public String upload() {
		logger.info("上传照片");
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String picUrl = null;
		try {
			picUrl = saveDir + (saveDir.endsWith("/") ? "" : "/") + (new Date()).getTime() +  picFileName.substring(picFileName.lastIndexOf(".")).trim().toLowerCase();
			String webRoot = WebUtils.getRealPath(request.getSession().getServletContext(), "");
			CoreFileUtils.uploadFile(pic, (webRoot + picUrl), CharsetConstant.CHARSET_UTF8);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		JSONObject rs = new JSONObject();
		rs.put("fileUrl", picUrl);
		super.writeRs(response, rs);
		return null;
	}
	
	public String changePwdInput() {
		if (user != null && user.getId() != null) {
			user = userService.get(user.getId());
		} else {
			logger.error("修改用户密码，编码为空");
			super.setErrorMessage("修改用户密码，编码不能为空");
			return "failure";
		}
		return "changePwdInput";
	}
	
	public String changePwd() {
		if (user != null && user.getId() != null) {
			if (StringUtils.isEmpty(user.getPassword())) {
				logger.error("密码为空");
				super.setErrorMessage("密码不能为空");
				return "inputForm";
			}
			if (StringUtils.isEmpty(conPassword)) {
				logger.error("确认密码为空");
				super.setErrorMessage("确认密码不能为空");
				return "inputForm";
			}
			if (!(user.getPassword()).equals(conPassword)) {
				logger.error("两次密码输入不一致");
				super.setErrorMessage("两次密码输入不一致");
				return "inputForm";
			}
			User sUser = userService.get(user.getId());
			sUser.setPassword(CoreStringUtils.md5(user.getPassword(), CharsetConstant.CHARSET_UTF8));
			sUser.setUpdatedTime(new Date());
			userService.update(sUser);
		} else {
			logger.error("修改用户密码，编码为空");
			super.setErrorMessage("修改用户密码，编码不能为空");
			return "failure";
		}
		super.setForwardUrl("/user/user.do?&page=" + page +"&username=" + username + "&uid=" + user.getId() + "&modFlag=0" + "&name=" + name + "&queryEnabledValue=" + queryEnabledValue);
		return "success";
	}
	
	public String dispatchApp() {
		if (user != null && user.getId() != null) {
			user = userService.get(user.getId());
			dispatchedApps = userService.findAppsByUser(user);
			if(dispatchedApps == null){
				dispatchedApps = Lists.newArrayList();
			}
			waitingApps = new ArrayList<App>();
			QueryParam queryParam = new QueryParam();
			queryParam.setPageBean(super.getPageBean());
			List<App> appList = appService.findList(queryParam);
			for (App app : appList) {
				boolean flag = true;
				for (App dispatchedApp : dispatchedApps) {
					if (app.getId().longValue() == dispatchedApp.getId().longValue()) {
						flag = false;
						break;
					}
				}
				if (flag) {
					waitingApps.add(app);
				}
			}
		} else {
			logger.error("分配子系统，编码为空");
			super.setErrorMessage("分配子系统，编码不能为空");
			return "failure";
		}
		return "dispatchApp";
	}
	
	public String dispatchRole(){
		if(user == null || user.getId() == null){
			logger.error("分配角色，用户为空");
			super.setErrorMessage("分配角色，用户不能为空");
			return "failure";
		}
		user = userService.get(user.getId());
		role = userService.findRoleByUser(user);
		roles = roleService.getAll();
		return "dispatchRole";
	}
	
	public String dispatchRoleManage(){
		if(user == null || user.getId() == null){
			logger.error("分配角色，用户为空");
			super.setErrorMessage("分配角色，用户不能为空");
			return "failure";
		}
		if(role == null || role.getId() == 0){
			logger.error("分配角色，角色为空");
			super.setErrorMessage("分配角色，角色不能为空");
			return "failure";
		}
		UserRole userRole = new UserRole(user.getId(),role.getId());
		userService.update(userRole);
		super.setForwardUrl("/user/user.do?&page=" + page +"&username=" + username + "&uid=" + user.getId() + "&modFlag=0" + "&name=" + name + "&queryEnabledValue=" + queryEnabledValue);
		logger.info("分配用户角色结束");
		return "success";
	}
	
	public String addApp() {
		if(user == null || user.getId() == null){
			logger.error("分配子系统，用户为空");
			super.setErrorMessage("分配子系统，用户不能为空");
			return "failure";
		}
		
		if(app == null || app.getId() == null){
			logger.error("分配子系统，编码为空");
			super.setErrorMessage("分配子系统，编码不能为空");
			return "failure";
		}
		UserApp userApp = new UserApp(user.getId(),app.getId());
		userService.manage(userApp);
		super.setForwardUrl("/user/user.do?action=dispatchApp&user.id=" + user.getId());
		return "forward";
	}
	
	public String delApp() {
		if(user == null || user.getId() == null){
			logger.error("分配子系统，用户为空");
			super.setErrorMessage("分配子系统，用户不能为空");
			return "failure";
		}
		
		if(app == null || app.getId() == null){
			logger.error("分配子系统，编码为空");
			super.setErrorMessage("分配子系统，编码不能为空");
			return "failure";
		}
		
		UserApp userApp = new UserApp(user.getId(),app.getId());
		userService.del(userApp);
		super.setForwardUrl("/user/user.do?action=dispatchApp&user.id=" + user.getId());
		return "forward";
	}
	
	/**
	 * 导出用户列表
	 * @return
	 */
	public String export() {
		logger.info("导出Excel开始");
		QueryParam qp = new QueryParam();
		PageBean pageBean = super.getPageBean();
		pageBean.setPageFlag(false);
		qp.setPageBean(pageBean);
		if(!StringUtils.isEmpty(name)){
			qp.setParameter(User.NAME_PROPERTY_NAME, name);
		}
		if(!StringUtils.isEmpty(username)){
			qp.setParameter(User.USER_NAME_PROPERTY_NAME, username);
		}
		List<User> userList = new ArrayList<User>();
		users = userService.findList(qp);
		if (users != null && users.size() > 0) {
			for (User user : users) {
				if (user.getEnabled() != null) {
					if (user.getEnabled().getValue() == EnabledStatus.ENABLED.getValue()) {
						userList.add(user);
					}
				} 
			}
			try {
				Workbook workBook = null;
				workBook = UsersExport.export(userList);
				setFileName("LJY_" + CoreDateUtils.formatDate(new Date()) + ".xls");
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				workBook.write(os);
				setInputStream(new ByteArrayInputStream(os.toByteArray()));
			} catch (Exception e) {
				logger.error("用户列表生成错误，原因：{}", e.getMessage());
				super.setErrorMessage("用户列表生成错误");
				return "failure";
			}
		} else {
			logger.error("没有查询出该用户的信息");
			super.setErrorMessage("没有查询出该用户的信息");
			return "failure";
		}
		logger.info("导出Excel结束");
		return "export";
	}

	public List<EnabledStatus> getEnabledStatusItems() {
		return EnabledStatus.getItemsForQuery();
	}

	public List<EnabledStatus> getEnabledStatusList() {
		return EnabledStatus.getItems();
	}
	
	public List<YesNoStatus> getYesNoStatusList() {
		return YesNoStatus.getItems();
	}
	
	public List<SexType> getSexTypeList() {
		return SexType.getItems();
	}
	
	public List<EducationDegreeType> getEducationDegreeTypeList() {
		return EducationDegreeType.getItems();
	}
	
	public List<MaritalStatus> getMaritalStatusList() {
		return MaritalStatus.getItems();
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public int getEnabledValue() {
		return enabledValue;
	}

	public void setEnabledValue(int enabledValue) {
		this.enabledValue = enabledValue;
	}

	public String getConPassword() {
		return conPassword;
	}

	public void setConPassword(String conPassword) {
		this.conPassword = conPassword;
	}

	public List<App> getDispatchedApps() {
		return dispatchedApps;
	}

	public void setDispatchedApps(List<App> dispatchedApps) {
		this.dispatchedApps = dispatchedApps;
	}

	public List<App> getWaitingApps() {
		return waitingApps;
	}

	public void setWaitingApps(List<App> waitingApps) {
		this.waitingApps = waitingApps;
	}

	public AppService getAppService() {
		return appService;
	}

	public void setAppService(AppService appService) {
		this.appService = appService;
	}

	public App getApp() {
		return app;
	}

	public void setApp(App app) {
		this.app = app;
	}

	public int getSexTypeValue() {
		return sexTypeValue;
	}

	public void setSexTypeValue(int sexTypeValue) {
		this.sexTypeValue = sexTypeValue;
	}

	public int getEducationDegreeValue() {
		return educationDegreeValue;
	}

	public void setEducationDegreeValue(int educationDegreeValue) {
		this.educationDegreeValue = educationDegreeValue;
	}

	public int getMaritalStatusValue() {
		return maritalStatusValue;
	}

	public void setMaritalStatusValue(int maritalStatusValue) {
		this.maritalStatusValue = maritalStatusValue;
	}

	public String getConOpPwd() {
		return conOpPwd;
	}

	public void setConOpPwd(String conOpPwd) {
		this.conOpPwd = conOpPwd;
	}

	public String getSaveDir() {
		return saveDir;
	}

	public void setSaveDir(String saveDir) {
		this.saveDir = saveDir;
	}

	public File getPic() {
		return pic;
	}

	public void setPic(File pic) {
		this.pic = pic;
	}

	public String getPicFileName() {
		return picFileName;
	}

	public void setPicFileName(String picFileName) {
		this.picFileName = picFileName;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public String getModFlag() {
		return modFlag;
	}

	public void setModFlag(String modFlag) {
		this.modFlag = modFlag;
	}

	public Long getUid() {
		return uid;
	}

	public void setUid(Long uid) {
		this.uid = uid;
	}

	public Integer getQueryEnabledValue() {
		return queryEnabledValue;
	}

	public void setQueryEnabledValue(Integer queryEnabledValue) {
		this.queryEnabledValue = queryEnabledValue;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}
}
